package ledger

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

/*
var m sync.Mutex
var TxID [][]byte
var TxRes []bool
*/

func ServerMuxInit() *http.ServeMux {
	mux := http.NewServeMux()

	mux.HandleFunc("/", index)

	// transaction execute interface
	mux.HandleFunc("/TxEXE", TransactionExe)

	return mux
}

func TransactionExe(w http.ResponseWriter, r *http.Request) {
	println("tx execute begin")

	// 定义基本结构
	var requestObject TxEXE
	var responseObject TxEXEResponse
	var err error

	// 分析请求数据
	body, _ := ioutil.ReadAll(r.Body)
	err = json.Unmarshal(body, &requestObject)
	if err != nil {
		println(err.Error())
		return
	}

	/*
		开始进行交易处理
	 */
	// 首先查询该交易是否已出现过，查询方式是查找TxID中是否有这笔交易的ID
	res := requestObject.Tx.Verify()

	// 构造 response body
	responseObject.Res = res

	// 暂停1秒钟以模拟交易执行
	time.Sleep(time.Duration(TxDelay)*time.Second)

	// 发送response
	ret,err := json.Marshal(responseObject)
	if err != nil {
		println("response marshal error\n", err.Error())
		return
	}
	n, err := w.Write(ret)
	if err != nil {
		println(err.Error())
		return
	} else if n != len(ret) {
		println("send to less")
		return
	}

	println("Tx "+ requestObject.Name +" execute success")
	return
}

func index(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()
	fmt.Println("Form: ", r.Form)
	fmt.Println("Path: ", r.URL.Path)
	fmt.Println(r.Form["a"])
	fmt.Println(r.Form["b"])
	for k, v := range r.Form {
		fmt.Println(k, "=>", v, strings.Join(v, "-"))
	}

	_,_ = fmt.Fprint(w, "It works !")
}